﻿using System;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Reflection;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace SelfMeter.Data
{
    public class MeterItem :
        INotifyPropertyChanged,
        IEditableObject
    {
        private DateTime _date;
        private double _data;

        [XmlAttribute]
        public DateTime Date
        {
            get { return _date; }
            set 
            {
                if (value != _date)
                {
                    _date = value;
                    RaisePropertyChanged("DateTime");
                }
            }
        }

        [XmlAttribute]
        public double Data
        {
            get { return _data; }
            set
            {
                if (value != _data)
                {
                    _data = value;
                    RaisePropertyChanged("Data");
                }
            }
        }

        #region ** INotifyPropertyChanged Members

        // this interface allows bounds controls to react to changes in the data objects.

        void RaisePropertyChanged(string propertyName)
        {
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, e);
        }

        #endregion
        #region IEditableObject Members

        // this interface allows transacted edits (user can press escape to restore previous values).

        MeterItem _clone;
        public void BeginEdit()
        {
            _clone = (MeterItem)this.MemberwiseClone();
        }
        public void EndEdit()
        {
            _clone = null;
        }
        public void CancelEdit()
        {
            if (_clone != null)
            {
                foreach (var p in this.GetType().GetRuntimeProperties())
                {
                    if (p.CanRead && p.CanWrite)
                    {
                        p.SetValue(this, p.GetValue(_clone, null), null);
                    }
                }
            }
        }

        #endregion
    }

    public class MeterDefinition
    {
        [XmlAttribute]
        public Guid ID = Guid.Empty;
        [XmlAttribute]
        public string Name;
        public string Description;
        [XmlAttribute]
        public string Unit;
        public List<MeterItem> MeterData;
    }
}